package com.cman777.springc.monitor.interceptor;

import io.prometheus.client.Counter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chenzhicong
 * @time 2021/1/12 17:41
 */
public class MonitorInterceptor  extends HandlerInterceptorAdapter {

    private Counter requestTotalCountCollector;
    public MonitorInterceptor(Counter requestTotalCountCollector){
        this.requestTotalCountCollector = requestTotalCountCollector;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if(HandlerMethod.class.isAssignableFrom(handler.getClass())) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            requestTotalCountCollector.labels(request.getRequestURI(), handlerMethod.getMethod().getName()).inc();
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
